package com.blog.controller;

import com.blog.entity.Article;
import com.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.tautua.markdownpapers.Markdown;
import org.tautua.markdownpapers.parser.ParseException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;

@Controller
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;


    @RequestMapping("/upload")
    public void ArticleUpload(MultipartFile file){

        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);

    }

    @RequestMapping("/index")
    public String index(Model model) {
        List<Article> articles = articleService.articleList();
        for (Article article : articles) {
//            System.out.println(article.getCategory());
//            System.out.println(articles);
        }
        model.addAttribute("articles", articles);
        return "views/index";
    }
 /*   *//**
     * 导航栏条件查询
     * @param category
     * @param model
     * @param displayName
     * @return
     */

    @RequestMapping("/column/{displayName}/{category}")
    public String column(@PathVariable("category") String category, Model model, @PathVariable("displayName") String displayName) {
        model.addAttribute("articles", articleService.getArticlesByCategoryName(category));
        model.addAttribute("displayName", displayName);
        return "views/columnPage";
    }

    /**
     * 页面详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/detail/{id}/{category}")
    public String detail(@PathVariable("id") Integer id, Model model) {
        Article article = articleService.getArticleById(id);
//        System.out.println(article.getContent());
        Markdown markdown = new Markdown();
        try {
            StringWriter out = new StringWriter();
            markdown.transform(new StringReader(article.getContent()), out);
            out.flush();
            article.setContent(out.toString());

        } catch (ParseException e) {
            e.printStackTrace();
        }
        model.addAttribute("article", article);
        return "views/detail";
    }
}
